package com.cook.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cook.dto.user.UserDTO;
import com.cook.entity.User;
import com.cook.mapper.UserMapper;
import com.cook.service.UserService;
import com.cook.vo.admin.ALLUserVO;
import com.cook.vo.admin.AllUserDetailVO;
import com.cook.vo.user.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    public AllUserDetailVO getUserInfoById(Long userId) {
        log.info("查询用户信息: userId={}", userId);

        try {
            AllUserDetailVO userInfo = userMapper.selectUserDetailById(userId);
            if (userInfo == null) {
                log.warn("用户不存在: userId={}", userId);
                throw new RuntimeException("用户不存在");
            }
            log.info("查询用户信息成功: userId={}", userId);
            return userInfo;
        } catch (Exception e) {
            log.error("查询用户信息失败: userId={}", userId, e);
            throw new RuntimeException("查询用户信息失败");
        }
    }

    @Transactional
    public boolean updateUser(UserDTO userDTO) {
        log.info("更新用户信息: userId={}", userDTO.getUserId());

        try {
            // DTO 转 Entity
            User user = new User();
            BeanUtils.copyProperties(userDTO, user);

            int result = userMapper.updateUserById(user);
            boolean success = result > 0;

            if (success) {
                log.info("用户信息更新成功: userId={}", userDTO.getUserId());
            } else {
                log.warn("用户信息更新失败: userId={}", userDTO.getUserId());
            }

            return success;
        } catch (Exception e) {
            log.error("更新用户信息失败: userId={}", userDTO.getUserId(), e);
            throw new RuntimeException("更新用户信息失败");
        }
    }

}